<template>
  <div>
    <el-upload
      action="#"
      list-type="picture-card"
      :class="{showphoto:fileList.length>0}"
      :file-list="fileList"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :on-change="onChange"
      :http-request="nload"
      :before-upload="beforeupload"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-progress v-if="progress>0&&progress<100" :percentage="progress" status="success" :show-text="false" style="width: 150px" />
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
var cos = new COS({
  SecretId: 'AKIDDEzTheJhoeEXZKo290ZrsdEclfKjriIb',
  SecretKey: '3qMccNs76qMdeOs4ze29zYqsd7KGvJTN'
})
export default {
  data() {
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      fileList: [],
      progress: 0
    }
  },
  methods: {
    onChange(file, newfileList) {
      this.fileList = [...newfileList]
    },
    handleRemove(file, fileList) {
      this.progress = 0
      this.fileList = [...fileList]
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    nload(files) {
      const file = files.file
      cos.putObject({
        Bucket: 'hm63-1306480966', /* 必须 */
        Region: 'ap-guangzhou', /* 存储桶所在地域，必须字段 */
        Key: Date.now() + file.name, /* 必须 */
        StorageClass: 'STANDARD',
        Body: file, // 上传文件对象
        onProgress: (progressData) => {
          this.progress = progressData.percent * 100
        }
      }, (err, data) => {
        console.log(111, err || data)
        if (!err) {
          this.fileList[0].url = 'https://' + data.Location
          this.fileList[0].status = 'success'
        }
      })
    },
    beforeupload(file) {
      const arr = ['image/png', 'image/jpeg']
      if (!arr.includes(file.type)) {
        this.$message.error('只支持png格式的图片')
        return false
      }
      const size = 500 * 1024
      if (file.size > size) {
        this.$$message.error('图片大小不可超过5m')
        return false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .showphoto{
 .el-upload--picture-card{
   display: none;
 }
}
</style>
